import re
from typing import List, Dict, Any
from pathlib import Path

class RISParser:
    """RIS文件解析器"""
    
    @staticmethod
    def parse_ris_file(file_path: str) -> List[Dict[str, Any]]:
        """
        解析RIS文件，返回文献列表
        
        Args:
            file_path: RIS文件路径
            
        Returns:
            包含文献信息的字典列表
        """
        entries = []
        current_entry = {}
        
        try:
            # 标准化路径
            normalized_path = str(Path(file_path).resolve())
            with open(normalized_path, 'r', encoding='utf-8') as file:
                lines = file.readlines()
                
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                    
                # 检查是否是新的条目开始
                if line.startswith('TY  - '):
                    # 保存前一个条目
                    if current_entry:
                        entries.append(current_entry)
                    # 开始新条目
                    current_entry = {'type': line[6:]}
                elif line.startswith('ER  -'):
                    # 条目结束
                    if current_entry:
                        entries.append(current_entry)
                    current_entry = {}
                elif '  - ' in line:
                    # 解析字段
                    parts = line.split('  - ', 1)
                    if len(parts) == 2:
                        field_code = parts[0]
                        field_value = parts[1]
                        
                        # 处理多值字段
                        if field_code in current_entry:
                            if isinstance(current_entry[field_code], list):
                                current_entry[field_code].append(field_value)
                            else:
                                current_entry[field_code] = [current_entry[field_code], field_value]
                        else:
                            current_entry[field_code] = field_value
            
            # 添加最后一个条目
            if current_entry:
                entries.append(current_entry)
                
        except Exception as e:
            print(f"解析RIS文件时出错: {e}")
            return []
            
        return entries
    
    @staticmethod
    def write_ris_file(entries: List[Dict[str, Any]], file_path: str) -> bool:
        """
        将文献列表写入RIS文件
        
        Args:
            entries: 文献信息字典列表
            file_path: 输出文件路径
            
        Returns:
            是否成功写入
        """
        try:
            # 标准化路径并确保目录存在
            normalized_path = Path(file_path).resolve()
            normalized_path.parent.mkdir(parents=True, exist_ok=True)
            
            with open(normalized_path, 'w', encoding='utf-8') as file:
                for entry in entries:
                    # 写入类型
                    file.write(f"TY  - {entry.get('type', 'JOUR')}\n")
                    
                    # 写入其他字段
                    for field_code, field_value in entry.items():
                        if field_code == 'type':
                            continue
                            
                        if isinstance(field_value, list):
                            for value in field_value:
                                file.write(f"{field_code}  - {value}\n")
                        else:
                            file.write(f"{field_code}  - {field_value}\n")
                    
                    # 写入条目结束标记
                    file.write("ER  -\n\n")
                    
            return True
            
        except Exception as e:
            print(f"写入RIS文件时出错: {e}")
            return False
    
    @staticmethod
    def extract_journal_info(entry: Dict[str, Any]) -> Dict[str, str]:
        """
        从文献条目中提取期刊信息
        
        Args:
            entry: 文献条目字典
            
        Returns:
            包含期刊信息的字典
        """
        journal_info = {}
        
        # 提取期刊名称 - 优先使用T2字段，然后是JO和JF字段
        journal_info['title'] = entry.get('T2', entry.get('JO', entry.get('JF', '')))
        
        # 提取ISSN
        issn = entry.get('SN', '')
        if issn:
            # 处理多值ISSN（列表）
            if isinstance(issn, list):
                # 取第一个ISSN
                issn = issn[0] if issn else ''
            
            if issn:
                # 清理ISSN格式
                issn = re.sub(r'[^0-9X-]', '', issn.upper())
                if len(issn) == 9 and issn[4] == '-':
                    journal_info['issn'] = issn
                elif len(issn) == 8:
                    journal_info['issn'] = f"{issn[:4]}-{issn[4:]}"
                else:
                    journal_info['issn'] = issn
        
        # 提取年份
        year = entry.get('PY', '')
        if year:
            journal_info['year'] = str(year)
        
        return journal_info 